package drafthj.javase.concurrent.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉
 * 〈功能详细描述〉
 *
 * @author drafthj
 * @date 2021/7/20
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class CombineTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> taskOne = CompletableFuture.supplyAsync(() -> {
            System.out.println(getThreadName() + " taskOne start.....");
            sleep(2);
            return 1;
        });
        CompletableFuture<Integer> taskTwo = CompletableFuture.supplyAsync(() -> {
            System.out.println(getThreadName() + " taskTwo start.....");
            sleep(1);
            return 1;
        });
        CompletableFuture<Integer> result = taskOne.thenCombine(taskTwo, (f1, f2) -> {
            System.out.println(getThreadName() + " combine start.....");
            return f1 + f2;
        });
        System.out.println(result.get());
    }

    private static void sleep(long timeout) {
        try {
            TimeUnit.SECONDS.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static String getThreadName() {
        return Thread.currentThread().getName();
    }
}
